package hot100.除自身以外数组的乘机;

/**
 * @author llt
 * @date 2025/4/25
 */
public class Test {
    public int[] productExceptSelf(int[] nums) {
        int length = nums.length;

        // i元素左边和右边的乘积
        int[] r = new int[length];
        int[] l = new int[length];

        // i == 0时 i左边没有元素 领 r[0] = 1
        r[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            r[i] = r[i - 1] * nums[i - 1];
        }

        // i == length - 1时 i右边没有元素 领 l[length - 1] = 1
        l[length - 1] = 1;
        for (int i = length - 2; i >= 0; i--) {
            l[i] = l[i + 1] * nums[i + 1];
        }

        // 求结果
        int[] answer = new int[length];
        for (int i = 0; i < nums.length; i++) {
            answer[i] = r[i] * l[i];
        }

        return answer;
    }
}
